//
//  YZMWebViewService.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/22.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMWebViewService.h"
#import "YZMWebViewController.h"
#import "YZMAlertView.h"
#import "YZClient.h"
#import "YZMCheckService.h"
#import "YZMShareService.h"
#import "YZMAppHelper.h"
#import "YZMHomeBannerModel.h"
#import <AFURLRequestSerialization.h>

#define sYZMWebviewRequestDeviceName         @"source"
#define sYZMWebviewRequestDeviceValue         @"IOSAPP"
#define YZMCHECKSERVICE [YZMCheckService sharedService]

@implementation YZMWebViewService

+ (void)openGuide{
    
    [YZMCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":@"app/index.html#/guide",@"title":@"新手引导",@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}]}];
}

+ (void)openSuggestionCenter{
    
    [YZMHCMInstance pushViewControllerWithName:@"suggestionEnter" andParams:@{@"urlString":@"/app/index.html#/help",@"title":@"客服中心",@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}],@"rightDic":@{@"image":@"icon_tel_service", @"selector":@"phoneCallForService"}}];
}


+ (void)openTradeRule:(YZM_TRADE_TYPE)tradeType{
    
    NSString *urlString = @"app/index.html#/tradeRule";
    NSString *title = @"A股交易规则";
    
    switch (tradeType) {
        case YZM_TRADE_TYPE_FOR_A_STOCK:
        case YZM_TRADE_TYPE_FOR_A_STOCK_FREE:
            urlString = @"app/index.html#/tradeRule";
            title = @"A股交易规则";
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_D:
            urlString = @"app/index.html#/TDTradeRule";
            title = @"T+D A股交易规则";
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:
            urlString = @"app/index.html#/ylbTradeRule";
            title = @"盈利宝交易规则";
            break;
        default:
            break;
    }
    [YZMHCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":urlString,@"title":title,@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}]}];
}

+ (void)openFeeStandard:(YZM_TRADE_TYPE)tradeType {
    
    NSString *urlString = @"app/index.html#/agreementSaletor";
    switch (tradeType) {
        case YZM_TRADE_TYPE_FOR_A_STOCK_D:
            urlString = @"app/index.html#/agreementTDSaletor";
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:
            urlString = @"app/index.html#/ylbAgreementInvestor";
            break;
        default:
            break;
    }
    [YZMHCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":urlString,@"title":@"协议",@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}]}];
}

+ (void)openCooperationDelegate{
    
    [YZMHCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":@"app/index.html#/agreementInvestor",@"title":@"协议",@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}]}];
}

+ (void)openCooperationDelegateWithTradeID:(long long)tradeID withType:(YZM_TRADE_TYPE)tradeType; {
    
    NSString *urlString = @"app/index.html#/agreementTDInvestor";
    
    switch (tradeType) {
        case YZM_TRADE_TYPE_FOR_A_STOCK:
             urlString = @"app/index.html#/agreementInvestor";
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_D:
            urlString = @"app/index.html#/agreementTDInvestor";
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:
            urlString = @"app/index.html#/ylbAgreementInvestor";
            break;
        default:
            break;
    }
    
    [YZMHCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":urlString,@"title":@"协议",@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName},@{sYZMWebviewParamName:@"tradeID",sYZMWebviewParamValue:@(tradeID)}]}];
}

+ (void)openRegisterAgreement {
    
    [YZMHCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":@"app/index.html#/agreementRegister",@"title":@"协议",@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}]}];
}

/*一分钟了解操盘*/
+ (void)openOuterDiscTeaching{
    
    [YZMHCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":@"app/index.html#/introduce",@"title":@"一分钟了解微策略",@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}]}];
}

/*快捷支付充值页面*/
+ (void)openFastConfirmViewWithURLString:(NSString *)urlString{
    
    [YZMHCMInstance pushViewControllerWithName:@"YZMFastPayConfirmViewController" andParams:@{@"urlString":urlString, @"type":@(YES),@"title":@"快捷支付",@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}]}];
}

+ (void)openFastConfirmViewWithString:(NSString *)string{
    [YZMHCMInstance pushViewControllerWithName:@"YZMFastPayConfirmViewController" andParams:@{@"urlString":string, @"type":@(NO),@"title":@"快捷支付",@"webParams":@[]}];
}

+ (void)openFastConfirmViewWithDic:(NSDictionary *)dic{
    NSDictionary *dicMiddle = [dic objectForKey:@"dataMap"];
    NSArray *arr = [dicMiddle.allKeys sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in arr) {
        if ([key isEqualToString:@"sign"]) {
            NSString *valueStr = [dicMiddle objectForKey:key];
            NSString *str = AFPercentEscapedStringFromString(valueStr);
            NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:key,sYZMWebviewParamName,str,sYZMWebviewParamValue, nil];
            [array addObject:dic2];
        }else{
            NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:key,sYZMWebviewParamName,[dicMiddle objectForKey:key],sYZMWebviewParamValue, nil];
            [array addObject:dic2];
        }
    }
    
    [YZMHCMInstance pushViewControllerWithName:@"YZMFastPayConfirmViewController" andParams:@{@"urlString":[[dic objectForKey:@"pay_url"] stringByAppendingString:@"kuaisuPay"], @"type":@(NO),@"title":@"快捷支付",@"webParams":array}];
    
}

static NSString * AFPercentEscapedStringFromString(NSString *string) {
    static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
    static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
    
    NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
    [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
    
    // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028
    // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
    
    static NSUInteger const batchSize = 50;
    
    NSUInteger index = 0;
    NSMutableString *escaped = @"".mutableCopy;
    
    while (index < string.length) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wgnu"
        NSUInteger length = MIN(string.length - index, batchSize);
#pragma GCC diagnostic pop
        NSRange range = NSMakeRange(index, length);
        
        // To avoid breaking up character sequences such as 👴🏻👮🏽
        range = [string rangeOfComposedCharacterSequencesForRange:range];
        
        NSString *substring = [string substringWithRange:range];
        NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
        [escaped appendString:encoded];
        
        index += range.length;
    }
    
    return escaped;
}

+ (void)openBannerWithDic:(NSDictionary *)dic {
    
    if (dic[@"urlEvent"]) {
        
        [YZMHCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":dic[@"bannerEvent"][@"url"],@"title":dic[@"title"], @"urlEvent":dic[@"urlEvent"], @"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}]}];
    } else {
        
        [YZMHCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":dic[@"bannerEvent"][@"url"],@"title":dic[@"title"], @"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}]}];
    }
}

+ (void)openAgreementTradeDelegate {

    [YZMHCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":@"app/index.html#/agreementTrade",@"title":@"协议",@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}]}];
}

+ (BOOL)openAppMethodWithUrl:(NSURL *)url {
    
    if (!url) {
        
        return NO;
    }
    
    NSArray *array = [url.absoluteString componentsSeparatedByString:@":"];
    if (array.count != 2) return NO;
    
    if ([YZMHomeBannerModel tradeParam:[@"yztz:" stringByAppendingString:array[1]] withDic:nil]) {
        
        return YES;
    }
    
    if ([[url.absoluteString lowercaseString] hasSuffix:[@"://ycl.yztz.com/simTrade" lowercaseString]]) {
        //模拟炒股入口
        [YZMCHECKSERVICE checkForSimulate];
        return YES;
        
    }else if ([[url.absoluteString lowercaseString] hasSuffix:[@"://ycl.yztz.com/actFree" lowercaseString]]){
        //免费体验入口
        [YZMCHECKSERVICE checkForFreeExpericence];
        return YES;
    }else if ([[url.absoluteString lowercaseString] hasSuffix:[@"://ycl.yztz.com/actTrade" lowercaseString]]) {
        //一元实盘入口
        [YZMCHECKSERVICE checkForOneYuan];
        return YES;
    }else if ([[url.absoluteString lowercaseString] hasSuffix:[@"://ycl.yztz.com/TDTrade" lowercaseString]]){
        [YZMCHECKSERVICE checkForTD];
        return YES;
    }
    return NO;
}


+ (void)openOneYuan {
    
    [YZMHCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":@"app/index.html#/oneYuanIntroduce",@"title":@"一元实盘",@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}], @"rightDic":@{@"image":@"icon_share", @"selector":@"sharedOneYuan"}}];
    
}

+ (void)openFreeExperience{
     [YZMHCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":@"app/index.html#/freeExp",@"title":@"免费体验",@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}], @"rightDic":@{@"image":@"icon_share", @"selector":@"sharedFreeEx"}}];
}

+(void)openSimulate {
    
    [YZMHCMInstance pushViewControllerWithName:@"webView" andParams:@{@"urlString":@"app/index.html#/simulateStock",@"title":@"炒股大赛",@"webParams":@[@{sYZMWebviewParamValue:sYZMWebviewRequestDeviceValue, sYZMWebviewParamName:sYZMWebviewRequestDeviceName}], @"rightDic":@{@"image":@"icon_share", @"selector":@"sharedSimulate"}}];
}

#pragma mark h5页面右上角按钮方法

+ (instancetype)sharedService
{
    static YZMWebViewService *sInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sInstance = [[self alloc] init];
    });
    
    return sInstance;
}


- (BOOL)containUrlStr:(NSString *)urlStr {
    
    if ([urlStr containsString:@"app/index.html#/oneYuanIntroduce"]) {
        
        [YZMWebViewService openOneYuan];
        return YES;
    }
    
    if ([urlStr containsString:@"app/index.html#/simulateStock"]) {
        
        [YZMWebViewService openSimulate];
        return YES;
    }
    
    return NO;
}

- (void)sharedOneYuan {
    [[YZMShareService sharedService] showSharePageTable:@{@"title":@"人人有份，免费领2000元", @"describe":@"你炒股，我出资，实盘操作，盈利全归您，亏损算我们", @"url":[URL_BASE_STRING stringByAppendingString:@"/app/index.html#/oneYuanIntroduce"]}];
}

- (void)sharedFreeEx{
     [[YZMShareService sharedService] showSharePageTable:@{@"title":@"免费体验", @"describe":@"免费体验，赚取红包可以抵交易综合费", @"url":[URL_BASE_STRING stringByAppendingString:@"/app/index.html#/freeExp"]}];
}

- (void)sharedSimulate {
    
    [[YZMShareService sharedService] showSharePageTable:@{@"title":@"万元悬赏：寻找最牛操盘手", @"describe":@"微策略炒股大赛，不只是玩玩", @"url":[URL_BASE_STRING stringByAppendingString:@"/app/index.html#/simulateStock"]}];
}

- (void)phoneCallForService{
    
    [YZMAppHelper callServicePhone];
}

@end
